package com.epoint.mobileoa.ui.photo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.epoint.mobileoa.R;
import com.epoint.mobileoa.adapter.PhotoListAdp;
import com.epoint.mobileoa.bizlogic.SuperView;
import com.epoint.mobileoa.tools.AlertHelp;
import com.epoint.mobileoa.tools.SDCard;
import com.epoint.mobileoa.tools.ToastHelp;

/**
 * 图片预览
 * 
 * @author lilin
 * @date 2011-12-3 上午09:34:31
 * @ClassName: ListPicView
 */
public class PhotoListView extends SuperView {
	private ListView photo_lv;// 图片列表
	private PhotoListAdp photoAdp;
	public static int photoIndex;// 图片的下标
	public static Uri[] photoURL;// 图片的URL

	public static List<String> pathsList;// 存放图片路径的List
	public String fileName[];
	private Bitmap bitmap = null;// 原位图
	private Bitmap smallbitmap = null;// 缩小的位图
	private ImageView preView_iv;// 预览

	public static final int ITEM0 = Menu.FIRST;
	public static final int ITEM1 = Menu.FIRST + 1;
	public static final int ITEM2 = Menu.FIRST + 2;
	public static final int ITEM3 = Menu.FIRST + 3;
	private Handler handler;
	private Map<Integer, Boolean> isSelected;// 选中的
	public static List<String> chooseFileList = new ArrayList<String>();
	private String index[];

	private Button confirm_btn;
	private Button delMarked_btn;
	private Button delAll_btn;

	// 刷新照片列表
	public void freshphoto_lv() {
		new Thread() {
			public void run() {
				doInHandler();
			};
		}.start();

	}
	

	public void doInHandler() {
		handler.post(new Runnable() {
			public void run() {
				pathsList = SDCard.getImagePathFromSDCard(getResources()
						.getString(R.string.photoPath_default));

				photoAdp = new PhotoListAdp(getApplicationContext(), pathsList);
				photo_lv.setAdapter(photoAdp);
				isSelected = new HashMap<Integer, Boolean>();
				for (int i = 0; i < pathsList.size(); i++) {
					isSelected.put(i, false);
				}
				PhotoListAdp.isSelected = isSelected;
				final Object data = getLastNonConfigurationInstance();// 得到横屏时临时存储的数据
				if (data == null) {// 为空重新加载
					new getImagesFromSD().execute();
				} else {
					final LoadImg[] photos = (LoadImg[]) data;
					if (photos.length == 0) {
						new getImagesFromSD().execute();
					}
					for (LoadImg photo : photos) {
						addImage(photo);
					}
				}

			}
		});
	}

	private void addImage(LoadImg... value) {
		for (LoadImg image : value) {
			photoAdp.addPhoto(image);// 把图片添加到适配器里面，以便调整图片的属性
			photoAdp.notifyDataSetChanged();
		}
	}

	// 读取sdcard上的图片
	class getImagesFromSD extends AsyncTask<Object, LoadImg, Object> {
		protected Object doInBackground(Object... params) {
			photoURL = new Uri[pathsList.size()];// 声明photoURL的长度
			for (int i = 0; i < pathsList.size(); i++) {
				String path = pathsList.get(i);
				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inSampleSize = 2;
				bitmap = BitmapFactory.decodeFile(path, options);
				if (bitmap != null) {
					// 将原来的位图缩小
					smallbitmap = Bitmap.createScaledBitmap(bitmap, 35, 35,
							true);
					bitmap.recycle();// 释放内存
					if (smallbitmap != null) {
						publishProgress(new LoadImg(smallbitmap));
					}
				}
			}
			return null;
		}

		public void onProgressUpdate(LoadImg... value) {
			addImage(value);
		}

		// 当加载完时停止标题栏的进度圈
		protected void onPostExecute(Object result) {
			m_Dialog.dismiss();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.radio_button1:// 删除选定
			deleteMarked();
			break;
		case R.id.radio_button2:// 全部删除
			deleteAll();
			break;
		case R.id.radio_button0:// 选中
			selectMarked();
			break;
		default:
			break;
		}
	}

	/**
	 * @author lilin
	 * @date 2012-3-11 下午01:52:25
	 * @annotation 选中标记
	 */
	private void selectMarked() {
		chooseFileList.clear();
		String temp = "";
		for (int i = 0; i < isSelected.size(); i++) {
			if (isSelected.get(i) == true) {
				temp = temp + i + ";";
			}
		}
		String index[] = temp.split(";");
		if (index.length > 0 && !index[0].equals("")) {
			for (int i = 0; i < index.length; i++) {
				String path = pathsList.get(Integer.valueOf(index[i]));
				chooseFileList.add(path);
			}
		}
//		startActivity(new Intent(WXZJ_PhotoListView.this,WXZJ_MailSendView.class));
		finish();
	}

	/**
	 * @author lilin
	 * @date 2012-3-11 下午01:51:31
	 * @annotation
	 */
	private void deleteAll() {

		if (pathsList.size() > 0)
		// 判断有数据可删除
		{
			Builder builder = new AlertDialog.Builder(PhotoListView.this);
			builder.setTitle("确定要删除全部吗？");
			builder.setIcon(R.drawable.epoint2);
			builder.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {

							for (int i = 0; i < pathsList.size(); i++) {
								String path = pathsList.get(i);
								SDCard.deleteFile(path);
							}
							ToastHelp.showToast(getApplicationContext(),
									"删除全部成功!");
							// 刷新
							freshphoto_lv();

						}
					});
			builder.setNegativeButton("取消", null);
			builder.create().show();

		} else {
			Toast.makeText(getApplicationContext(), "列表为空！", 5000).show();
		}

	}

	/**
	 * @author lilin
	 * @date 2012-3-11 下午01:50:32
	 * @annotation 删除选定
	 */
	private void deleteMarked() {

		String temp = "";
		for (int i = 0; i < isSelected.size(); i++) {
			if (isSelected.get(i) == true) {
				temp = temp + i + ";";
			}
		}
		index = temp.split(";");
		if (index.length > 0 && !index[0].equals(""))
		// 判断有无数据可删除
		{
			Builder builder = new AlertDialog.Builder(PhotoListView.this);
			builder.setTitle("确定要删除选中吗？");
			builder.setIcon(R.drawable.epoint2);
			builder.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							for (int i = 0; i < index.length; i++) {
								String path = pathsList.get(Integer
										.valueOf(index[i]));
								SDCard.deleteFile(path);
							}
							ToastHelp.showToast(getApplicationContext(),
									"删除选定成功!");
							// 刷新
							freshphoto_lv();

						}
					});
			builder.setNegativeButton("取消", null);
			builder.create().show();

		} else if (pathsList.size() == 0) {
			Toast.makeText(getApplicationContext(), "列表为空!", 5000).show();
		} else if (index[0].equals("")) {
			Toast.makeText(getApplicationContext(), "请选择要删除的照片!", 5000).show();

		}
	}

	// 销毁
	protected void onDestroy() {
		super.onDestroy();
	}

	// 暂停
	protected void onPause() {
		super.onPause();
	}

	// 重新启动
	protected void onRestart() {
		super.onRestart();
	}

	// Resume
	protected void onResume() {
		// initView();
		super.onResume();
	}

	public int getLayoutInt() {
		return R.layout.qwt_photolistview;
	}

	public void initControls() {
		// 固定屏幕为竖屏
		if (PhotoListView.this.getRequestedOrientation() == -1) {
		} else {
			if (PhotoListView.this.getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
				PhotoListView.this
						.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			}
		}

		showDialog_wait("正在加载图片...");
		handler = new Handler();
		photo_lv = (ListView) findViewById(R.id.test_lv);
		preView_iv = (ImageView) findViewById(R.id.preview_iv);
		confirm_btn = (Button) findViewById(R.id.radio_button0);
		delMarked_btn = (Button) findViewById(R.id.radio_button1);
		delAll_btn = (Button) findViewById(R.id.radio_button2);
		confirm_btn.setOnClickListener(this);
		delMarked_btn.setOnClickListener(this);
		delAll_btn.setOnClickListener(this);
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 2;
		preView_iv.setImageBitmap(BitmapFactory.decodeResource(getResources(),
				R.drawable.preview3, options));
		freshphoto_lv();
		isSelected = PhotoListAdp.isSelected;
		// ListView的单击事件
		photo_lv.setOnItemClickListener(this);
		top_right_bt.setVisibility(View.VISIBLE);
		top_right_bt.setText("拍照");
		top_right_bt.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(PhotoListView.this,
						TakePhotoView.class);
				startActivity(intent);
				finish();
			}
		});

		top_left_bt.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				back_deal();
			}
		});

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view,
			int position, long id) {
		// 加载图片预览
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 2;
		bitmap = BitmapFactory.decodeFile(pathsList.get(position), options);
		preView_iv.setImageBitmap(bitmap);
	}

	public String setTitle() {
		return "图片列表";
	}

	// 按键返回
	public void KEYCODE_BACK() {
		back_deal();
	}

	@Override
	public void refresh(Object... param) {
		// TODO Auto-generated method stub

	}

	public void back_deal() {
		AlertHelp.ShowAlert(this, "确认返回吗？",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						finish();
					}
				});
	}


	@Override
	public void refreshForNewTask(int TaskId,Object... param) {
	}

}
